<template>
  <div class="tab-hte-layout">
    <home-nav :userData="userinfo"></home-nav>
    <div class="content"> 
      <template>
        <side-menu
          mode="inline"
          :menus="menus"        
          :theme="navTheme"
          :titleList="titleList"
          :titleType="titleType"
          :collapsed="collapsed"
          @toggle="menusToggle"
          @handleChange="menusHandleChange"
          @onSearch="menusOnSearch"
          :collapsible="true">
        </side-menu>
      </template>
      <a-layout
        :class="[layoutMode, `content-width-${contentWidth}`]"
        :style="{ paddingLeft: fixSiderbar && isDesktop() ? `${sidebarOpened ? 200 : 80}px` : '0' }">
        <a-layout-content :style="{ height: '100%', paddingTop: fixedHeader ? '59px' : '0' }">
          <template>
            <contextmenu :itemList="menuItemList" :visible.sync="menuVisible" style="z-index: 9999;" @select="onMenuSelect"/>    
            <a-tabs
              @contextmenu.native="e => onContextmenu(e)"
              v-if="multipage"
              :active-key="activePage"
              class="tab-layout-tabs"
              :hide-add="true"
              type="editable-card"
              @change="changePage"
              @tabClick="tabCallBack"
              @edit="editPage">
              <a-tab-pane :id="page.fullPath" :key="page.fullPath" v-for="page in pageList" :closable="pageList.length > 1">
                <span slot="tab" :pagekey="page.fullPath">{{ page.meta.title }}</span>
              </a-tab-pane>                         
            </a-tabs>
            <!-- <template>
              <a-dropdown placement="bottomCenter"> 
                <a-icon type="more" class="menu-more" @click="e => e.preventDefault()"/>
                <a-menu slot="overlay">
                  <a-menu-item>
                    <a href="javascript:;" @click="toggleFullScreen($event)">全屏</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a href="javascript:;" @click="closeCurrent()">关闭当前</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a href="javascript:;" @click="closeOthers(activePage)">关闭其他</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a href="javascript:;" @click="closeAll">关闭全部</a>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </template> -->
            
            <div class="menu-content">                  
              <keep-alive v-if="multipage">
                <router-view v-if="reloadFlag"/>
              </keep-alive>
              <template v-else>
                <router-view v-if="reloadFlag"/>
              </template>                  
            </div>
          </template>
        </a-layout-content>
      </a-layout>
    </div>
  </div>
</template>

<script>
  import Contextmenu from '@/components/menuHte/Contextmenu'
  import { mixin, mixinDevice } from '@/utils/mixin.js'
  import { triggerWindowResizeEvent } from '@/utils/util'
  import SideMenu from '@/components/menuHte/SideMenu'
  import Vue from 'vue'
  import { CACHE_INCLUDED_ROUTES } from "@/store/mutation-types"
  import HomeNav from '@/components/layouts/HomeNav'
  import { reportRouterMap } from "@/config/router.config"
  import { mapActions } from 'vuex'
  import {filterHasPermission} from '@/utils/hasPermission'

  export default {
    name: 'TabHteLayout',
    components: {
      Contextmenu,
      SideMenu,
      HomeNav,
    },
    mixins: [mixin, mixinDevice],
    data() {
      return {
        userinfo: {
          info: this.$store.getters.userInfo,
          module: 'TabHteLayout',
        },
        pageList: [],
        linkList: [],
        activePage: '',
        menuVisible: false,
        menuItemList: [
          { key: '4', icon: 'reload', text: '刷 新' },
          { key: '1', icon: 'arrow-left', text: '关闭左侧' },
          { key: '2', icon: 'arrow-right', text: '关闭右侧' },
          { key: '3', icon: 'close', text: '关闭其它' }
        ],
        reloadFlag:true,
        collapsed: false, // 侧边栏是否收缩，false展开 true收缩
        menus: [], // 侧边栏菜单，动态显示内容
        titleList: [
          {title: '项目报表', value: '1'},
          // {title: '主数据维护', value: '2'},
          // {title: '系统管理', value: '3'},
        ],
        titleType: '',
      }
    },    
    provide(){
      return{
        closeCurrent:this.closeCurrent
      }
    },    
    computed: {
      multipage() {
        return this.$store.state.app.multipage
      },
    },
    created() {
      // 侧边栏
      this.collapsed=!this.sidebarOpened      
      // 初始选中菜单
      this.initRouer()         
    },
    mounted() {
    },
    watch: {
      '$route': function(newRoute) {
        let exists = false
        this.pageList.forEach(p => {
          if(p.fullPath==this.$route.fullPath){
            exists = true;
          }
        });
        if(!exists){
          this.pageList.push(this.$route)
          this.linkList.push(this.$route.fullPath)
        }
        this.activePage = this.$route.fullPath
        // this.activePage = newRoute.fullPath
        // if (this.linkList.indexOf(newRoute.fullPath) < 0) {
        //   this.linkList.push(newRoute.fullPath)
        //   this.pageList.push(Object.assign({},newRoute))
        // } else if (this.linkList.indexOf(newRoute.fullPath) >= 0) {
        //   let oldIndex = this.linkList.indexOf(newRoute.fullPath)
        //   let oldPositionRoute = this.pageList[oldIndex]
        //   this.pageList.splice(oldIndex, 1, Object.assign({},newRoute,{meta:oldPositionRoute.meta}))
        // }
        
      },
      'activePage': function(key) {
        this.$router.push(key)
        // let index = this.linkList.lastIndexOf(key)
        // let waitRouter = this.pageList[index]                
        // if (waitRouter.fullPath !== this.$route.fullPath) {
        //   this.$router.push(Object.assign({}, waitRouter))
        // }
        this.changeTitle(this.$route.meta.title)
      },
      'multipage': function(newVal) {
        if(this.reloadFlag){
          if (!newVal) {
            this.linkList = [this.$route.fullPath]
            this.pageList = [this.$route]
          }
        }
      },
      sidebarOpened(val) {
        this.collapsed = !val
      },
    },

    methods: { 
      /**
       * 初始化选中菜单 
       */   
      initRouer() {
        let currentRoute = Object.assign({}, this.$route)
        currentRoute.meta = Object.assign({}, currentRoute.meta)
        let storeKey = 'route:title:' + currentRoute.fullPath
        let routeTitle = this.$ls.get(storeKey)
        if (routeTitle) {
          currentRoute.meta.title = routeTitle
        }
        this.pageList.push(currentRoute)
        this.linkList.push(currentRoute.fullPath)
        this.activePage = currentRoute.fullPath
        // 设置初始标题select
        const obj = this.titleList.find(item =>{
          return  item.value === currentRoute.meta.parentGround || item.value === currentRoute.ground
        })
        this.titleType = obj ? obj.value : this.titleList[0].value
        // 设置初始菜单     
        this.getReportRouterMap()
      },
      changeTitle(title) {
        let projectTitle = "海芯科技平台"
        document.title = title + ' · ' + projectTitle
      },
      /**
       * 切换tabs菜单 
       */
      changePage(key) {
        this.activePage = key
      },
      tabCallBack() {
        this.$nextTick(() => {
         setTimeout(()=>{           
           triggerWindowResizeEvent()
         },20)
        })
      },
      editPage(key, action) {
        this[action](key)
      },
      
      onContextmenu(e) {
        const pagekey = this.getPageKey(e.target)
        if (pagekey !== null) {
          e.preventDefault()
          this.menuVisible = true
        }
      },
      getPageKey(target, depth) {
        depth = depth || 0
        if (depth > 2) {
          return null
        }
        let pageKey = target.getAttribute('pagekey')
        pageKey = pageKey || (target.previousElementSibling ? target.previousElementSibling.getAttribute('pagekey') : null)
        return pageKey || (target.firstElementChild ? this.getPageKey(target.firstElementChild, ++depth) : null)
      },
      onMenuSelect(key, target) {
        let pageKey = this.getPageKey(target)
        switch (key) {
          case '1':
            this.closeLeft(pageKey)
            break
          case '2':
            this.closeRight(pageKey)
            break
          case '3':
            this.closeOthers(pageKey)
            break
          case '4':
            this.routeReload()
            break
          default:
            break
        }
      },    
      /**
       * 关闭当前 
       */  
      closeCurrent(){        
        this.remove(this.activePage);
      },
      remove(key) {
        if (this.pageList.length === 1) {
          this.$message.warning('这是最后一页，不能再关闭了啦')
          return
        }
        let removeRoute = this.pageList.filter(item => item.fullPath == key)
        this.pageList = this.pageList.filter(item => item.fullPath !== key)
        let index = this.linkList.indexOf(key)
        this.linkList = this.linkList.filter(item => item !== key)
        index = index >= this.linkList.length ? this.linkList.length - 1 : index
        this.activePage = this.linkList[index]
        
        //关闭页面则从缓存cache_included_routes中删除路由，下次点击菜单会重新加载页面
        let cacheRouterArray = Vue.ls.get(CACHE_INCLUDED_ROUTES) || []
        if (removeRoute && removeRoute[0]) {
          let componentName = removeRoute[0].meta.componentName
          if(cacheRouterArray.includes(componentName)){
            cacheRouterArray.splice(cacheRouterArray.findIndex(item => item === componentName), 1)
            Vue.ls.set(CACHE_INCLUDED_ROUTES, cacheRouterArray)
          }
        }       
      },
      /**
       * 关闭全部 
       */  
      closeAll(){
        this.linkList.splice(0, this.linkList.length)
        this.pageList.splice(0, this.pageList.length)
      },
      /**
       * 关闭其他
       */ 
      closeOthers(pageKey) {
        if(this.linkList.length==1){
          return
        }
        const index = this.linkList.indexOf(pageKey)
        this.linkList = this.linkList.slice(index, index + 1)
        this.pageList = this.pageList.slice(index, index + 1)
        this.activePage = this.linkList[0]
      },
      /**
       * 关闭左侧 
       */
      closeLeft(pageKey) {
        let index = this.linkList.indexOf(pageKey)
        if(index === 0){
          return
        }
        this.linkList = this.linkList.slice(index)
        this.pageList = this.pageList.slice(index)
        if (this.linkList.indexOf(this.activePage) < 0) {
          this.activePage = this.linkList[0]
        }
      },
      /**
       * 关闭右侧 
       */
      closeRight(pageKey) {
        let index = this.linkList.indexOf(pageKey)
        if(index === this.linkList.length -1){
          return
        }
        this.linkList = this.linkList.slice(0, index + 1)
        this.pageList = this.pageList.slice(0, index + 1)
        if (this.linkList.indexOf(this.activePage < 0)) {
          this.activePage = this.linkList[this.linkList.length - 1]
        }
      },

      /**
       * 刷新 
       */
      routeReload(){
        this.reloadFlag = false
        let ToggleMultipage = "ToggleMultipage"
        this.$store.dispatch(ToggleMultipage,false)
        this.$nextTick(()=>{
          this.$store.dispatch(ToggleMultipage,true)
          this.reloadFlag = true
        })
      },

      /**
       * 全屏 
       */
      toggleFullScreen(){
        const el = document.getElementById("app")
        el.webkitRequestFullscreen();
      },
      /**
       * 菜单收缩按钮
       */
      ...mapActions(['setSidebar']),
      menusToggle() {
        this.collapsed = !this.collapsed
        this.setSidebar(!this.collapsed)
        triggerWindowResizeEvent()
      },
      /**
       * 根据标题动态切换菜单 
       */
      menusHandleChange(value){
        this.titleType = value
        this.getReportRouterMap('clear')
      },
      getReportRouterMap(type){        
        this.menus = this.getCurrentRouter()
        // 清空原有缓存路由及tab页
        if(type){
          this.closeAll()
          this.$router.push({ path: this.menus[0].path })
        }      
      },
      getCurrentRouter(){
        const routeCopy = Object.assign([], reportRouterMap)        
        const routeItem = routeCopy.filter(item=>{
          // 项目清单报告不加report，兼容旧的权限 modify by dr 20220830
          if (item.limit && item.limit == 'projectListReport:list') {
            return filterHasPermission(item.limit) 
          }
          // 设置权限
          if(item.limit){
            return (
              item.ground === this.titleType &&
              !item.blank && 
              filterHasPermission('report:'+item.limit) 
            )
          }else{
            if(item.children && item.children.length){
              item.children = item.children.filter(data =>{              
                return !data.limit || (data.limit && filterHasPermission('report:'+data.limit))
              })              
            }
            return item.ground === this.titleType && !item.blank   
          }
        })
        return routeItem.length ? routeItem : reportRouterMap
      },
      /**
       * 菜单实时搜索
       */      
      menusOnSearch(value){
        const currentRouter = this.getCurrentRouter() // 正在显示的菜单
        const menuCopy = JSON.parse(JSON.stringify(currentRouter));                
        if(!value){
          this.menus = currentRouter
        }else{          
          this.menus = this.handleSearch(menuCopy, value) // 根据搜索内容展示菜单
        }
      },
      handleSearch(tree, value){
        let removeArr = []
        for(let i = 0; i< tree.length; i++){
          let node = tree[i]
          this.searchTree(node, i, value, removeArr)
        }
        for(let j=removeArr.length-1; j>=0 ;j--){
          tree.splice(removeArr[j], 1)
        }
        return tree
      },
      searchTree(node, index, value, removeArr){
        let children = node.children
        if(children && children.length > 0){
          let innderArr = []
          for(let i=0;i<children.length;i++){
            this.searchTree(children[i], i, value, innderArr)
          }
          if(!node.meta.title.includes(value)){
            for(let j=innderArr.length-1; j>=0 ; j--){
              children.splice(innderArr[j], 1)
            }
            if(node.children.length === 0){
              removeArr.push(index)
            }
          }
        }else{
          if(!node.meta.title.includes(value)){
            removeArr.push(index)
          }
        }
      },
    }
  }
</script>
<style lang="less" scoped>
  @hoverbg: #4f81c4;
  /deep/ .tab-layout-tabs.ant-tabs {    
    border: none;
    background-color: #f5f5f5;
    padding: 5px 20px 0 10px;
    &.ant-tabs-card {
      @12th: 12px !important;
      .ant-tabs-tab {
        padding: 0 22px 0 10px !important;
        margin-right: 6px !important;
        background-color: #e8ebf1 !important;border: 1px solid #e8ebf1 !important;
        border-radius: 6px 6px 0px 0px;
        height: 36px;color: #666;
        .ant-tabs-close-x {
          width: @12th;
          height: @12th;
          opacity: 1 !important;
          cursor: pointer !important;
          font-size: @12th;
          margin: 0 !important;
          position: absolute;
          top: 37%;
          right: 6px;
          color: #666;
          &:hover{color: @hoverbg;}
        }
        &.ant-tabs-tab-active{
          background-color: #739ccc !important;color: #fff;
          .ant-tabs-close-x {color: #fff;}
          &:hover{opacity: 0.8;}
        }
        &:not(.ant-tabs-tab-active):hover{
          color: @hoverbg;
        }
      }
      > .ant-tabs-bar {margin: 14px 0 0 0;border-bottom: none;
      }
      .ant-tabs-card-bar .ant-tabs-nav-container{height: 36px;}
    }
    .ant-tabs-tab-arrow-show{width: 20px;
      &:hover .anticon {color: @hoverbg;}
    }
    .ant-tabs-nav-container-scrolling{padding: 0 20px;}
  }
  .tab-hte-layout{height: 100%;background-color: #f5f5f5;
    .content{padding: 13px;background-color: #f5f5f5;display: flex;
      >.ant-layout{overflow-x: auto;background-color: #fff;min-height: 84.7vh;}
      .menu-content{height: calc(100% - 54px);border: 1px solid #e2e2e2;}
    }
    .sider{
      &.light {box-shadow: none;background-color: #4f81c4;color: #fff;}
    }
    main.ant-layout-content{position: relative;}
    .menu-more{position:absolute;top: 28px;right: 0px;width: 20px;height: 20px;font-size: 19px;transform: rotate(90deg);cursor: pointer;
      &:hover{color: @hoverbg;}
    }
    /deep/ .ant-menu-inline-collapsed{width: 60px;}
  }  
  /deep/ .ant-layout-sider-collapsed{
    @wid: 60px;
    width: @wid !important;
    min-width: @wid !important;
    max-width: @wid !important;
    .side-header{justify-content: center;
      >span{max-width: 0;max-height: 0;opacity: 0;}
    }
  }
</style>